package leetcode


fun main(args: Array<String>) {

}

fun mergeTwoLists(l1: ListNode?, l2: ListNode?): ListNode? {/*
    if (l1 == null && l2 == null)
        return l1
    val result = ListNode(0)
    var p = result
    var header1 = l1
    var header2 = l2
    while (header1 != null || header2 != null) {

        if (header1 != null && header2 != null) {
            if (header1.`val` > header2.`val`) {
                p.`val` = header2.`val`
                header2 = header2.next
            } else {
                p.`val` = header1.`val`
                header1 = header1.next
            }
            p.next = ListNode(0)
            p = p.next!!
        } else {

            var h = if (header1 != null) header1 else header2

            p.`val` = h!!.`val`
            while (h?.next != null) {
                h = h.next
                p.next = ListNode(0)
                p = p.next!!
                p.`val` = h!!.`val`
            }
            break


        }
    }

    return result*/


    var p: ListNode? = ListNode(0, null)

    var p1 = l1
    var p2 = l2

    val head = p

    while (p1 != null && p2 != null) {

        if (p1.`val` < p2.`val`) {
            p?.next = p1
            p1 = p1.next
        } else {
            p?.next = p2
            p2 = p2.next
        }

        p = p?.next
    }

    //有一个列表还没有访问完，直接拼在最后
    if (p1 != null)
        p?.next = p1

    if (p2 != null)
        p?.next = p2

    return head?.next
}

fun mergeTwoSortedListEx(l1: ListNode?, l2: ListNode?): ListNode? {
    if (l1 == null)
        return l2
    if (l2 == null)
        return l1


    var p = l1
    var s = l2

    var h: ListNode? = null

    while (p != null && s != null) {
        var node: ListNode?
        if (p.`val` > s.`val`) {

            node = p
            p = p.next
        } else {
            node = s
            s = s.next
        }

        if (h == null)

            h = node
        else h.next = node

    }

    if (p != null)
        h?.next = p

    if (s != null)
        h?.next = s

    return h


}